<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 分类参数操作提示 -->
      <el-alert title="注意：只允许为第三级分类设置相关的参数" type="warning" show-icon></el-alert>

      <!-- 选择商品分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="cateListChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tabs 标签页 -->
      <!-- v-model 选中的标签页 name 值 -->
      <!-- tab-click tab 页被选中时触发的事件 -->
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <!-- label 选项卡标题 -->
        <!-- name 选项卡别名，方便对选项卡进行操作 -->
        <!-- 添加动态参数的tabs -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加动态参数 -->
          <el-button
            type="primary"
            plain
            :disabled="isBtnDisabled"
            size="mini"
            @click="addDialogVisible = true"
          >动态参数</el-button>
          <el-table :data="manyTableData" border stripe style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 渲染已有的属性 -->
                <el-tag
                  type="warning"
                  closable
                  @close="removeParams(index, scope.row)"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                >{{ item }}</el-tag>
                <!-- 添加新的属性 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  size="mini"
                  type="success"
                  plain
                  @click="showEditDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  type="danger"
                  plain
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的tabs -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态属性 -->
          <el-button
            type="primary"
            plain
            :disabled="isBtnDisabled"
            size="mini"
            @click="addDialogVisible = true"
          >静态属性</el-button>
          <el-table :data="onlyTableData" border stripe style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="warning"
                  closable
                  @close="removeParams(index, scope.row)"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                >{{ item }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-edit"
                  size="mini"
                  type="success"
                  plain
                  @click="showEditDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  type="danger"
                  plain
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加属性以及参数的弹框 -->
      <el-dialog :title="'添加' + textTitle" :visible.sync="addDialogVisible" width="50%">
        <el-form :model="addParams" :rules="addParamsRules" ref="addParamsRef" label-width="100px">
          <el-form-item :label="textTitle" prop="attr_name">
            <el-input v-model="addParams.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParamsHandle">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改属性以及参数的弹框 -->
      <el-dialog
        :title="'修改' + textTitle"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editFormClose"
      >
        <el-form
          :model="editParams"
          :rules="editParamsRules"
          ref="editParamsRef"
          label-width="100px"
        >
          <el-form-item :label="textTitle" prop="attr_name">
            <el-input v-model="editParams.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParamsHandle">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      cateList: [], // 分类数据列表
      selectCateKeys: [], // 级联选择器选中以后的值
      // 级联选择器配置项
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      activeName: 'many', // tabs 选中的选项
      manyTableData: [],
      onlyTableData: [],
      addDialogVisible: false, // 控制添加参数的显示和隐藏
      // 添加动态参数或者静态属性
      addParams: {
        attr_name: ''
      },
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editDialogVisible: false, // 控制修改弹框的显示和隐藏
      // 编辑动态参数或者静态属性
      editParams: {
        attr_name: ''
      },
      editParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 调用获取商品分类的数据的方法
    this.getCatelist()
  },
  methods: {
    // 删除分类参数
    removeParams (i, paramsInfo) {
      paramsInfo.attr_vals.splice(i, 1)

      this.saveParams(paramsInfo)
    },

    // 参数编辑操作
    async saveParams (paramsInfo) {
      const { data: res } = await this.$http.put(
        `/categories/${paramsInfo.cat_id}/attributes/${paramsInfo.attr_id}`,
        {
          attr_name: paramsInfo.attr_name,
          attr_sel: paramsInfo.attr_sel,
          attr_vals: paramsInfo.attr_vals.join(' ')
        }
      )

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // this.getParamsData() -- 可以不加
      this.$message.success(res.meta.msg)
    },

    // 展示 Input 输入框
    showInput(paramsInfo) {
      paramsInfo.inputVisible = true

      // 想在整个DOM元素异步渲染以后。调用某一个方法
      this.$nextTick(() => {
        // 箭头函数无参数可以写()或者_
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // input 框失去焦点，按住 enter 键以后出发的事件
    async handleInputConfirm(paramsInfo) {
      console.log(paramsInfo)
      if (paramsInfo.inputValue.trim().length === 0) {
        paramsInfo.inputValue = ''
        paramsInfo.inputVisible = false

        return false
      }

      // 如果 inputValue 符合需求，就需要发起请求
      paramsInfo.attr_vals.push(paramsInfo.inputValue.trim())
      paramsInfo.inputValue = ''
      paramsInfo.inputVisible = false

      this.saveParams(paramsInfo)
    },

    // 因为 tabs 切换 和 级联选择器 事件，调用的是同一份接口，重复写一份代码容易造成代码的冗余，
    // 所以抽取成一个单独的方法，
    async getParamsData() {
      // 控制级联选择器的选择范围
      // 按照产品需求的要求，只允许为第三级分类设置相关的参数，
      // 一级和二级不能够进行设置
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }

      const { data: res } = await this.$http.get(
        `/categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },

    // 删除分类或者属性
    async deleteParams(attrId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消了删除')
      }

      const { data: res } = await this.$http.delete(
        `/categories/${this.cateId}/attributes/${attrId}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParamsData()
    },

    // 获取当前分类的具体信息
    // 参数 cateInfo 为使用 scope 传递过来的数据
    async showEditDialog(cateInfo) {
      // 根据接口文档，处理请求的路径和参数
      const { data: res } = await this.$http.get(
        `/categories/${this.cateId}/attributes/${cateInfo.attr_id}`,
        {
          params: { attr_sel: this.activeName }
        }
      )

      // 根据返回的状态码进行提示
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 请求成功后，将值赋值给编辑表单的数据对象，
      // 因为页面中使用了双向数据绑定，所以会展示到弹框中
      this.editParams = res.data
      this.editDialogVisible = true
    },

    // 修改动态参数以及静态属性
    editParamsHandle() {
      // 在发起编辑操作前，进行预校验
      this.$refs.editParamsRef.validate(async valid => {
        // 验证不通过，不执行后续的操作
        if (!valid) return
        // 验证通过以后，根据接口文档，发起请求即可
        // 参数在前面已经全部获取成功
        const { data: res } = await this.$http.put(
          `/categories/${this.cateId}/attributes/${this.editParams.attr_id}`,
          {
            attr_name: this.editParams.attr_name,
            attr_sel: this.activeName
          }
        )
        // 根据返回的状态码进行提示
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.editDialogVisible = false
      })
    },

    // 重置修改表单的操作
    editFormClose() {
      this.$refs.editParamsRef.resetFields()
    },

    // 添加动态参数以及静态属性
    addParamsHandle() {
      this.$refs.addParamsRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post(
          `/categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParams.attr_name,
            attr_sel: this.activeName
          }
        )

        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)

        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        this.getParamsData()
      })
    },

    // 重置添加参数的表单
    addFormClose() {
      this.$refs.addParamsRef.resetFields()
    },

    // tab 别选中时触发
    tabClick() {
      this.getParamsData()
    },

    // 级联选择器选中的值改变以后出发
    async cateListChange() {
      this.getParamsData()
    },

    // 获取商品分类的数据
    async getCatelist() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    }
  },
  computed: {
    // 控制按钮是否可禁用
    isBtnDisabled() {
      // 产品需求：如果级联选择器的长度不等于 3，说明是一级或者二级分类，这时候，添加按钮需要禁用
      if (this.selectCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 获取分类参数的 id
    cateId() {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2]
      }
      return null
    },
    textTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt,
.el-tabs,
.el-table {
  margin-top: 20px;
}

.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 150px;
}
</style>
